#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "framewindow.h"
#include <QDebug>
#include <QWidget>
#include <QScreen>
static HHOOK hook=nullptr;
static int i=0;
static MainWindow* mainwindow;

LRESULT CALLBACK mouseHookCallback(int code ,WPARAM wParam,LPARAM lParam){


    MOUSEHOOKSTRUCT *mhookstruct;   //鼠标HOOK结构体
    mhookstruct = reinterpret_cast<MOUSEHOOKSTRUCT*>(lParam);
    POINT pt = mhookstruct->pt;
    qDebug()<<i++<<" "<<pt.x<<" "<<pt.y;
    HWND win=WindowFromPoint(pt);
    if(win!=nullptr && reinterpret_cast<uint>(win)!=mainwindow->winId()){
        //::ShowWindow(win,SW_HIDE);
        WCHAR t[100];
        GetWindowText(win,t,100);
        QString s=QString::fromStdWString(t);
        RECT rect;
        GetWindowRect(win,&rect);
        qDebug()<<s;
        mainwindow->drawText(s);
        if(mainwindow->framewin!=nullptr){
            mainwindow->framewin->close();
            mainwindow->framewin->deleteLater();
        }
        mainwindow->framewin=new FrameWindow();
        mainwindow->framewin->setAttribute(Qt::WA_TranslucentBackground);
        mainwindow->framewin->setWindowFlag(Qt::FramelessWindowHint);
        mainwindow->framewin->setWindowFlag(Qt::WindowStaysOnTopHint);
        mainwindow->framewin->setWindowFlag(Qt::Tool);
        QRect re=QRect(rect.left,rect.top,rect.right-rect.left,rect.bottom-rect.top);
        qDebug()<<re;
        mainwindow->framewin->setGeometry(re);
        mainwindow->framewin->show();

    }
    return CallNextHookEx(hook,code,wParam,lParam);
}

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    setAttribute(Qt::WA_TranslucentBackground);
    setWindowFlag(Qt::FramelessWindowHint);
    setWindowFlag(Qt::WindowStaysOnTopHint);
    QScreen* screen=qApp->primaryScreen();
    resize((screen->size().width()-width())/2,(screen->size().height()-height()/2));
    mainwindow=this;
    ui->setupUi(this);
    mouseHook=::SetWindowsHookEx(WH_MOUSE_LL,mouseHookCallback,nullptr,0);
    hook=mouseHook;
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::drawText(QString s)
{
    ui->label->setText(s);
}

void MainWindow::closeEvent(QCloseEvent *)
{
    qApp->exit(0);
}
